
<template src="./tpl.html"></template>

<script>
import {CONSENT_SAVE_TEMPLATE,CONSENT_GET_TEMPLATE_INFO,CONSENT_GET_ZK_LIST} from "_SERVICES/api";
import { simDeepCopy, setStorage, getStorage } from "UTILS/util";
import {isvalidateNum2}from "UTILS/validate";

import draggable from "vuedraggable";
import draggableItem from "MODULES/CST/components/DraggableItem";
import componentsList from "./config";


export default {
  name: "setTemplate",
  components: {
    draggable,
    draggableItem,
  },
  watch: {},
  data() {
    return {
      componentsList: componentsList,
      consentList: [],
      formInline: {},
      activeItem: {},
      templateInfo:{
        TEMPLATE_MC:"",
        TID:"",
        ZKID:"",
        PX:""
    
      },
      ZK_LIST:[],
      visible: false,
      consentString:"",
      isMenuVisible: false,
      menuTop: 0,
      menuLeft: 0,
      showMenuItem:{},
      queryInfo:{},
      loading: false
    };
  },
  created() {
    // let info = JSON.parse(getStorage("consent_list"));
    // console.log(info)
    this.get_zkid_list()

    if (this.$route.query) {
      this.queryInfo = this.$route.query;
    }
    if(this.queryInfo.TID && this.queryInfo.TYPE) {
      this.get_template_info();
    }

  },
  mounted(){
    document.addEventListener("keydown", (event)=> {
      if (event.key === "Delete") {
        this.deleteItem();
      }
    });
  },
  methods: {
    get_template_info(){
      CONSENT_GET_TEMPLATE_INFO({
        TID: this.queryInfo.TID
      }).then((res)=>{
        console.log("获取模板详情",res)
        if(res.data.length) {
          let info =  res.data[0];
          console.log(info)
          this.templateInfo = {
            TEMPLATE_MC:this.queryInfo.TYPE==2?info.MC:"",
            ZKID:info.ZKID,
            TID: this.queryInfo.TYPE==2?info.TID:"",
            PX: info.PX
          }
          this.consentList = JSON.parse(info.TPL_FORMAT)
        
        }else{
          this.$message.error("未获取到对应的模板")
        }
      
      })
    },
    changeTemp(val){
      const newArray = this.tempList.filter(item => item.TEMPLATE_MC == val);
     
      console.log(newArray)
      this.consentList = newArray[0].consentList
      this.templateInfo.TEMPLATE_MC = newArray[0].TEMPLATE_MC;
      this.templateInfo.ZKID = newArray[0].ZKID;
    },
    clearTemplate(){
      this.consentList = [];
      this.activeItem = {}
    },
   
    addItem(item) {
      let obj = simDeepCopy(item);
      if (!obj.field_name) {
        obj.field_name = this.setfieldId();
      }
      this.consentList.push(obj);
      this.activeItem = obj;
    },
    deleteItem(){
      const indexToRemove = this.consentList.findIndex(item => item.field_name === this.activeItem.field_name);
      if (indexToRemove !== -1) {
        this.consentList.splice(indexToRemove, 1);
        this.activeItem = {}
      }
    },
    addOption() {
      this.activeItem.field_options.push({
        dm: "",
        mc: "",
      });
      if (this.activeItem.type == "checkbox" ) {
        this.activeItem.field_value = [];
      } else {
        this.activeItem.field_value = "";
      }
    },
    deleteOption(info_index) {
      this.activeItem.field_options.splice(info_index, 1);
      if (this.activeItem.type == "checkbox") {
        this.activeItem.field_value = [];
      } else {
        this.activeItem.field_value = "";
      }
    },
    //切换签名组件 签名身份 则关系字段要清空
    changeSignIdentity(){
      this.activeItem.field_value.sign_relation="";
    },
    getComponentItem(type){
      const newArray = this.componentsList.filter(item => item.type == type);
      if(newArray.length){
        return newArray[0]
      }else{
        return {}
      }
    },
    selectItem(item,index) {
      let info = {
        ... this.getComponentItem(item.type),
        ...item
      }
      this.$set(this.consentList,index,info);
      this.activeItem = info
    },
    setfieldId() {
      let num = 0;
      this.consentList.forEach((item) => {
        if (item && item.field_name.indexOf("field") > -1) {
          let index = (item.field_name.split("field")[1]);
          if(isvalidateNum2(index)) {
            index = Number(index);
            if (index >= num) {
              num = index;
            }
          }
        }
      });
      return `field${++num}`;
    },
    onDragStart1(event){
      //修改复制的组件
      event.item._underlying_vm_ = simDeepCopy(event.item._underlying_vm_);
      if(! event.item._underlying_vm_ .field_name) {
        event.item._underlying_vm_ .field_name = this.setfieldId();
      }
    },
    onDragEnd1(event) {
      console.log("onDragEnd1", event.item._underlying_vm_,event.newIndex );
      // this.consentList[event.newIndex] = simDeepCopy(event.item._underlying_vm_);
      // let info = this.consentList[event.newIndex];
      // if(!info.field_name) {
      //   info.field_name = this.setfieldId();
      // }
      this.activeItem =  event.item._underlying_vm_;
    },
    onDragEnd2(event) {
      console.log(this.consentList);
      console.log("onDragEnd2", event.newIndex);
    },
    showMenu(event,item,index){
      console.log(event,item,index)
      this.isMenuVisible = true;
      this.menuTop = event.clientY;
      this.menuLeft = event.clientX;
      this.showMenuItem  = simDeepCopy(item);

    },
    hideMenu() {
      this.isMenuVisible = false;
    },
    menuItemClicked(type) {
      let obj  = simDeepCopy(this.showMenuItem);
      if(type==1){ //复制
        obj.field_name = this.setfieldId();
        this.consentList.push(obj);
        this.activeItem = obj;
      }else if(type==2){//删除
        const indexToRemove = this.consentList.findIndex(item => item.field_name === this.showMenuItem.field_name);
        if (indexToRemove !== -1) {
          this.consentList.splice(indexToRemove, 1);
          if(this.showMenuItem.field_name== this.activeItem.field_name) {
            this.activeItem = {}
          }
         
        }
      }
      this.hideMenu();
    },
    preview(){
      this.visible = true;
      this.consentString =  JSON.stringify(this.consentList,['field_name','field_value','type','label','field_options','field_value_type',
                                                             'sign_img','sign_identity','sign_relation','sign_time','dm','mc','field_value_required','field_value_save'],2) 
    },
    get_zkid_list(){
      CONSENT_GET_ZK_LIST({

      }).then((res)=>{
        console.log("获取专科列表成功")
        this.ZK_LIST = res.data || []
      })
    },
    hasDuplicateIndex(array, indexKey) {
      const seenIndexes = new Set();
      for (const obj of array) {
        console.log(obj)
        const currentIndex = obj[indexKey];
        if (seenIndexes.has(currentIndex)) {
          return currentIndex; // 存在重复主索引
        }
        // 否则，将主索引值加入集合
        seenIndexes.add(currentIndex);
      }
      // 没有找到重复主索引
      return "";
    },
    saveTemplate() {
      const newArray = this.consentList.filter(item => item.field_name == "" || !item.field_name);
      console.log(newArray)
      if(newArray.length) {
        this.$message.error("存在字段名为空，请检查");
        return false;
      }


      let DuplicateIndex=  this.hasDuplicateIndex(this.consentList,'field_name');
      if(DuplicateIndex){
        this.$message.error(`存储重复的字段名称:${DuplicateIndex}，请检查`);
        return false
      }
      if(!this.templateInfo.TEMPLATE_MC) {
        this.$message.error(`同意书名称不能为空`);
        return false

      }
      if(!this.templateInfo.ZKID) {
        this.$message.error(`所属专科不能为空`);
        return false
      }
      console.log(this.consentList)
      this.loading = true;
      CONSENT_SAVE_TEMPLATE({
        TID : this.templateInfo.TID,	// 有则表示更新，没有则新增
        TPL_MC : this.templateInfo.TEMPLATE_MC,
        TPL_FORMAT : JSON.stringify(this.consentList),
        ZKID : this.templateInfo.ZKID,
        PX: this.templateInfo.PX
      }).then((res)=>{
        this.loading = false;

        console.log(res)
        this.$message.success("保存成功");
        if(!this.templateInfo.TID) {
          this.$router.push({
            path:'/templateList'
          })
        }

      

      }).catch((res)=>{
        this.loading = false;

      })
      // this.consentList.length = this.consentList.length-3;
     
      
      // console.log(this.consentList);
      // let obj  = {
      //   ...this.templateInfo,
      //   consentList: this.consentList
      // }
      // console.save(obj,`${this.templateInfo.TEMPLATE_MC}.js`)
      // setStorage({
      //   name: "consent_list",
      //   value: JSON.stringify(obj),
      // });
    },
  },
};
</script>

<style lang="less">
.set-template-html {
  .con {
    border-radius: 3px;
    box-sizing: border-box;
  }
  .con-middle {
    box-sizing: border-box;
  }
  .con-left {
    width: 240px;
    padding: 10px 10px;
    box-sizing: border-box;
  }
  .con-right {
    width: 400px;
    box-sizing: border-box;
  }
  .active {
    box-shadow: 0px 0px 2px #409eff;
  }
  .el-scrollbar__wrap {
    overflow-x: hidden !important;
  }
  .el-card__body {
    padding: 15px;
  }
  .el-card__header {
    padding: 10px 15px;
  }
  .pre-attr {
    //  whiteSpace: 'pre-wrap',fontSize:12,wordBreak:'break-word'

    white-space: pre-wrap;
    word-break: break-all;
  }
  .context-menu {
    position: fixed;
    background-color: #fff;
    border: 1px solid #efefef;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 5px 10px;
    cursor: pointer;
  }
}
</style>
